<template>
  <view class="main">
    <view class="login-form">
      <view class="con-form">
        <view class="form-text">IP地址</view>
        <u--input v-model="server.ip" border="bottom" placeholder="请输入服务器IP或域名" @blur="validateIp"></u--input>
        <view class="error-text" v-if="errors.ip">{{ errors.ip }}</view>
      </view>
      <view class="con-form">
        <view class="form-text">端口</view>
        <u--input v-model="server.port" border="bottom" placeholder="请输入端口号" type="number" @blur="validatePort"></u--input>
        <view class="error-text" v-if="errors.port">{{ errors.port }}</view>
      </view>
      
      <u-button 
        type="primary" 
        @click="testConnection" 
        :loading="testing"
        :disabled="!formValid"
        text="测试连接" 
        color="#315EBC"
        style="margin-top: 30rpx;">
      </u-button>
      
      <u-button 
        type="success" 
        @click="saveServer" 
        :disabled="!connectionSuccess || !formValid"
        text="保存设置" 
        color="#4CAF50"
        style="margin-top: 30rpx;">
      </u-button>
      
      <u-toast ref="uToast"></u-toast>
    </view>
  </view>
</template>

<script setup>
import { reactive, computed } from 'vue';
import { jumpPage } from '../../until';

const server = reactive({
  ip: '',
  port: '80'
});

const errors = reactive({
  ip: '',
  port: ''
});

const testing = ref(false);
const connectionSuccess = ref(false);

const formValid = computed(() => {
  return server.ip && server.port && !errors.ip && !errors.port;
});

function validateIp() {
  if (!server.ip) {
    errors.ip = '请输入IP地址';
    return false;
  }
  
  // 简单的IP/域名验证
  const ipRegex = /^((\d{1,3}\.){3}\d{1,3}|([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,})$/;
  if (!ipRegex.test(server.ip)) {
    errors.ip = '请输入有效的IP地址或域名';
    return false;
  }
  
  errors.ip = '';
  return true;
}

function validatePort() {
  if (!server.port) {
    errors.port = '请输入端口号';
    return false;
  }
  
  const portNum = parseInt(server.port);
  if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
    errors.port = '端口号必须在1-65535之间';
    return false;
  }
  
  errors.port = '';
  return true;
}

async function testConnection() {
  if (!validateIp() || !validatePort()) return;
  
  testing.value = true;
  connectionSuccess.value = false;
  
  try {
    const testUrl = `http://${server.ip}:${server.port}/testConnection`; // 替换为你的测试接口路径
    const response = await uni.request({
      url: testUrl,
      method: 'GET',
      timeout: 5000 // 5秒超时
    });
    if (response.statusCode === 200) {
      connectionSuccess.value = true;
      uni.showToast({
        title: '连接成功',
        icon: 'success'
      });
    } else {
      throw new Error('连接失败');
    }
  } catch (error) {
    console.error('连接测试失败:', error);
    uni.showToast({
      title: '连接失败，请检查设置',
      icon: 'none'
    });
    connectionSuccess.value = false;
  } finally {
    testing.value = false;
  }
}

function saveServer() {
  if (!connectionSuccess.value) return;
  
  uni.setStorageSync("server", server);
  uni.showToast({
    title: '保存成功',
    icon: 'success'
  });
  jumpPage("/login/index");
}

onShow(() => {
  let serverStore = uni.getStorageSync("server");
  if (serverStore) {
    server.ip = serverStore.ip;
    server.port = serverStore.port;
  }
  validateIp();
  validatePort();
});
</script>

<style lang="scss">
page {
  background: white;
}

.login-form {
  height: auto;
  margin: 50rpx 30rpx;
  border-radius: 30rpx;
  background: white;
  padding: 100rpx 30rpx 30rpx;

  .con-form {
    margin-bottom: 40rpx;

    .form-text {
      font-size: 32rpx;
      font-weight: 700;
      color: #315EBC;
      margin-bottom: 10rpx;
    }
    
    .error-text {
      color: #f56c6c;
      font-size: 24rpx;
      margin-top: 10rpx;
    }
  }
}
</style>